package protocol;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * DataOutputStream with custom send( CtfPacket ) function to 
 * process a packet's data into network byte order and send
 * in the expected order.
 * 
 * To be wrapped around a socket's output stream.
 * 
 * @author WHOMP
 */
public class CtfDataOutputStream extends DataOutputStream {

	/**
	 * Write each field of the CtfHeader as well as any
	 * message bytes onto the outgoing stream.
	 * 
	 * @param p CtfPacket
	 */
	public void send( CtfPacket p ) {
		try {
			// set body length
			if ( p.body != null ) {
				p.header.bodyLength = p.body.length;
			} else {
				p.header.bodyLength = 0;
			}
			byte[] headerInBytes = p.header.toNetworkByteArray();
			write( headerInBytes, 0, headerInBytes.length );
			/*
			writeShort( p.header.sender );
			System.err.println( p.header.sender );
			
			writeShort( p.header.msgType );
			System.err.println( p.header.msgType );
			
			writeShort( p.header.gameState );
			System.err.println( p.header.gameState );
			
			writeShort( p.header.bodyLength );
			System.err.println( p.header.bodyLength );
			
			writeShort( Conversions.booleanToInt( p.header.hasMoreFragments) );
			System.err.println( Conversions.booleanToShort( p.header.hasMoreFragments) );
			*/
			if ( p.body != null ) {
				write( p.body, 0, p.body.length );
				//System.err.println( new String( p.msg ) );
			}
		} catch ( IOException e ) {
			e.printStackTrace();
		}
	}
	
	/* Constructor */
	public CtfDataOutputStream( OutputStream out ) {
		super( out );
	}

}
